/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/
import {ajax, toast, cacheTools, print, output} from 'nc-lightapp-front';
import constants from '../../constants';

import ampub from 'ampub';
import fa from 'fa';
// import ampub from '../../../../../ampub/common/collection/release';
// import fa from '../../../../common/collection/release';

const {components, utils} = ampub;
const {fa_components} = fa;

const {openEquipCardByPk} = components.queryAboutUtils;
const {queryAboutVoucher} = components.queryVocherUtils;
const {showConfirm, MsgConst, showMessage, showErrorMessageByRes} = utils.msgUtils;
const {batchRefresh} = utils.listUtils;
const {getMultiLangByID} = utils.multiLangUtils;

const {CardLinkToBill} = fa_components.CardLinkToBillUtil;

import rowSelected from "./rowSelected";
import searchBtnClick from './searchBtnClick';
import {doDeleteBeforeCheck} from '../../validator';

const tableId = constants.AREA.LIST.GRID_AREA;
const BILL_SOURCE_TYPES = constants.BILL_SOURCE_TYPES;
const {
    REFRESH,
    DELETE,
    COPY,
    Attachment,
    QueryAboutCard,
    QueryAboutVoucher,
    QueryAboutBusiness,
    PRINT_CHILD,
    PRINT_NOCHILD,
    PRINT_LIST,
    Output
} = constants.LIST_BTNS.HEAD;

export default function buttonClick(props, id) {
    const that = this;
    switch (id) {
        //表头刷新
        case REFRESH:
            doRefresh(that);
            break;

        //表头复制
        case COPY:
            doCopy(that);
            break;

        //打印-带副卡
        case PRINT_CHILD:
            doPrintChild(that);
            break;

        //打印-不带副卡
        case PRINT_NOCHILD:
            doPrintNoChild(that);
            break;

        //打印-清单
        case PRINT_LIST:
            doPrintList(that);
            break;

        //输出
        case Output:
            doOutput(that);
            break;

        //表头删除
        case DELETE:
            showConfirm.call(this, props, {
                type: MsgConst.Type.DelSelect,
                beSureBtnClick: () => {
                    batchDelete(props);
                }
            });

            break;

        //联查设备卡片
        case QueryAboutCard:
            queryAboutCard(props);
            break;

        //附件
        case Attachment:
            attachment(props);
            break;

        //联查凭证
        case QueryAboutVoucher:
            let appcode = this.props.pageConfig.appid;
            queryAboutVoucher(props, tableId, 'pk_card', appcode, true);
            break;

        //联查来源单据
        case QueryAboutBusiness:
            billreview.call(that);
            break;

        //卡片交易类型按钮点击, pagecode就是交易类型
        default:
            openCard(that, id);
            break;
    }
}

//根据选择的交易类型打开卡片
function openCard(that, id) {
    linkToCard(that.props, {
        status: constants.UISTATE.ADD,
        transiType: id,
        pagecode: id
    });
}

//行删除
function deleteLine(props, row) {
    let checkRet = doDeleteBeforeCheck(row.values);
    if (checkRet) {
        showMessage(props, {content: checkRet, color: 'danger'});
    } else {
        doDelete(props, [row]);
    }
}

//批量删除
function batchDelete(props) {
    let rowsWillDel = props.table.getCheckedRows(tableId);
    if (rowsWillDel && rowsWillDel.length) {
        rowsWillDel = rowsWillDel.map((row) => row.data);
        let checkErrs = [];
        rowsWillDel.forEach((row) => {
            let err = doDeleteBeforeCheck(row.values);
            if (err) {
                checkErrs.push(err);
            }
        });

        if (checkErrs.length) {
            if (checkErrs.length === 1) {
                toast({content: checkErrs[0], color: 'danger'});
            } else {
                toast({
                    color: 'danger',
                    groupOperation: true,
                    groupOperationMsg: checkErrs,
                    TextArr: [getMultiLangByID('amcommon-000005'),
                        getMultiLangByID('amcommon-000006'),
                        getMultiLangByID('amcommon-000007')] /* 国际化处理： ['展开', '收起', '关闭'] */
                });
            }

        } else {
            doDelete(props, rowsWillDel);
        }
    } else {
        /*国际化处理：请选择需要删除的单据*/
        showMessage(props, {type: MsgConst.Type.ChooseDelete});

    }
}

function doCopy(that) {
    let rows = that.props.table.getCheckedRows(tableId);
    if (rows && rows.length) {
        const pk_card = rows[0].data.values.pk_card.value;
        that.facardCopy.showCopyCardDialog(that, pk_card, rows[0].data.values);
    } else {
        /*国际化处理：请选择需要复制的单据*/
        showMessage(that.props, {type: MsgConst.Type.ChooseCopy});
    }
}

/**
 * 执行删除
 *
 * @props props
 * @param rows 需要删除的行数组
 */
function doDelete(props, rows) {
    if (rows) {
        //获取pk、ts
        let pks = [];
        let tss = [];
        rows.forEach((row) => {
            pks.push(row.values.pk_card.value);
            tss.push(row.values.ts.value);
        });

        const data = {
            pks: pks.join(','),
            tss: tss.join(',')
        };
        ajax({
            url: constants.URL.DELETE,
            data,
            success: (res) => {
                let {success, data} = res;
                if (success) {
                    let {allSuccess, message, suceessArr, failure} = data;
                    if (failure) {
                        showMessage(props, {content: failure, color: 'danger'});
                    } else {
                        if (message && message.length === 1) {
                            toast({
                                color: 'success',
                                title: message[0]
                            });
                        } else {
                            toast({
                                color: 'danger',
                                content: message.shift(),
                                groupOperation: true,
                                groupOperationMsg: message,
                                TextArr: [getMultiLangByID('amcommon-000005'),
                                    getMultiLangByID('amcommon-000006'),
                                    getMultiLangByID('amcommon-000007')] /* 国际化处理： ['展开', '收起', '关闭'] */

                            });
                        }

                        //删除成功后, 同步缓存和表格数据
                        let {deleteCacheId} = props.table;
                        if (suceessArr && suceessArr.length) {
                            let pkcardsToDel = [];
                            suceessArr.map((pk_cardAndpk_accbook) => {
                                //删除缓存
                                deleteCacheId(tableId, pk_cardAndpk_accbook);
                                //删除表格中的数据
                                let pk_card = pk_cardAndpk_accbook.split('_')[0];
                                pkcardsToDel.push(pk_card);
                            });

                            let indexsToDel = [];
                            let allData = props.table.getAllTableData(tableId);
                            allData.rows.map((row, index) => {
                                const pk_card = row.values.pk_card.value;
                                if (pkcardsToDel.includes(pk_card)) {
                                    indexsToDel.push(index);
                                }
                            });
                            props.table.deleteTableRowsByIndex(tableId, indexsToDel);
                        }
                        //更新按钮状态
                        rowSelected(props, tableId);
                    }
                }
            },
            error: (err) => {
                showErrorMessageByRes(props, res);
            }
        });
    }
}

//跳转到卡片态
function linkToCard(props, param = {}) {
    let defaultParam = {
        status: constants.UISTATE.BROWSE
    };
    let am_source = props.getUrlParam('am_source');
    let menu_name = props.getUrlParam('nccloud_menu_name_self');

    param = Object.assign(defaultParam, param);
    if (am_source) {
        param.am_source = am_source;
    }
    if (menu_name) {
        param.nccloud_menu_name_self = menu_name;
    }
    props.pushTo('/card', param);
}

//刷新
function doRefresh(that) {
    batchRefresh.call(that, that.props, searchBtnClick);
}

function doPrintChild(that) {
    let nodekey = '201201504A_child';
    let url = constants.URL.PRINT_CARD;
    doPrint(that, nodekey, url);
}

function doPrintNoChild(that) {
    let nodekey = '201201504A_nochild';
    let url = constants.URL.PRINT_CARD;
    doPrint(that, nodekey, url);
}

function doPrintList(that) {
    let nodekey = '201201504A_list';
    let url = constants.URL.PRINT_LIST;
    doPrint(that, nodekey, url);
}

//打印
function doPrint(that, nodekey, printUrl) {
    let printData = getPrintData.call(that, that.props, 'print');
    printData.nodekey = nodekey || printData.nodekey;
    let url = printUrl || constants.URL.PRINT_CARD;
    if (!printData) {
        /*国际化处理：请选择需要打印的数据*/
        showMessage(that.props, {type: MsgConst.Type.ChoosePrint});
        return;
    }
    print(
        'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
        url, // 后台打印服务url
        printData
    );
}

//输出
function doOutput(that) {
    let printData = getPrintData.call(that, that.props, 'output');
    //输出默认为不带副卡的模板
    printData.nodekey = '201201504A_nochild';
    if (!printData) {
        /*国际化处理：请选择需要输出的数据*/
        showMessage(that.props, {type: MsgConst.Type.ChooseOutput});
        return;
    }
    output({
        url: constants.URL.PRINT_CARD,
        data: printData
    });
}

/*
 * 获取打印数据
 */
function getPrintData(props, outputType = 'print') {
    const {pageConfig} = this.props;
    let printNodekey = null;

    let checkedRows = props.table.getCheckedRows(tableId);
    if (!checkedRows || checkedRows.length == 0) {
        return false;
    }
    let pks = [];
    checkedRows.map((item) => {
        let pk_card = item.data.values['pk_card'].value;
        let pk_accbook = item.data.values['pk_accbook'].value;
        pks.push(pk_card + '_' + pk_accbook);
    });
    let printData = {
        filename: pageConfig.title, // 文件名称
        appcode: '201201504A',
        nodekey: printNodekey, // 模板节点标识
        oids: pks, // 需要打印数据主键
        outputType // 输出类型
    };
    return printData;
}

//联查设备卡片
function queryAboutCard(props) {
    let checkedRows = props.table.getCheckedRows(tableId);
    if (!checkedRows || !checkedRows.length) {
        /*国际化处理：请选择需要联查的卡片*/
        showMessage(props, {content: getMultiLangByID('201201504A-000030'), color: 'warning'});
        return;
    }
    //默认选择第一条进行联查
    let row = checkedRows[0];
    let pk_equip = row.data.values.pk_equip && row.data.values.pk_equip.value;
    if (pk_equip) {
        openEquipCardByPk(props, pk_equip);
    } else {
        /*国际化处理：选中的数据中第一条没有关联设备卡片*/
        showMessage(props, {content: getMultiLangByID('201201504A-000031'), color: 'warning'});
    }
}

/**
 * 附件上传
 * @param  props
 */
function attachment(props) {
    let checkedrows = props.table.getCheckedRows(tableId);
    if (!checkedrows || !checkedrows.length) {
        /*国际化处理：请选择一行数据*/
        showMessage(props, {type: MsgConst.Type.ChooseOne});
        return;
    }
    // billNo 是资产编码
    let billNo = checkedrows[0].data.values['asset_code'].value;
    // billNo 是卡片主键
    let billId = checkedrows[0].data.values['pk_card'].value;
    props.ncUploader.show('uploader', {
        billId: 'fa/card/' + billId,
        billNo
    });
}

//单据追溯
function billreview() {
    let checkedrows = this.props.table.getCheckedRows(tableId);
    if (!checkedrows || !checkedrows.length) {
        /*国际化处理：请选择一行数据*/
        showMessage(null, {type: MsgConst.Type.ChooseOne});
        return;
    }

    //默认选择第一条进行联查
    let row = checkedrows[0];
    //获取卡片来源
    let bill_source = row.data.values.bill_source && row.data.values.bill_source.value;
    //获取来源主键
    let pk_bill_src = row.data.values.pk_bill_src && row.data.values.pk_bill_src.value;

    if (bill_source === BILL_SOURCE_TYPES.inventory_src) {
        let bill_code_src = row.data.values.bill_code_src && row.data.values.bill_code_src.value;
        pk_bill_src = pk_bill_src + '<:>' + bill_code_src;
    }

    if (bill_source !== BILL_SOURCE_TYPES.handin_src) {
        if (pk_bill_src) {
            CardLinkToBill.call(this, this.props, pk_bill_src, bill_source);
        } else {
            /*国际化处理：该单据的来源单据号错误*/
            showMessage(this.props, {content: getMultiLangByID('201201504A-000021'), color: 'warning'});
        }
    } else {
        /*国际化处理：该单据没有来源单据*/
        showMessage(this.props, {content: getMultiLangByID('201201504A-000022'), color: 'warning'});
    }

}

export {doRefresh, linkToCard, deleteLine};

/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/